package com.sc.web.gwt.server.util;

import com.sc.web.gwt.server.persistence.UserAccountPersistence;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

public class AccountCodeGenerator {
    public static String getAccountCode() {
        UserAccountPersistence userAccountPersistence = new UserAccountPersistence();
        List<String> currentInitCodeList = new ArrayList<String>();
        currentInitCodeList = userAccountPersistence.getAllAccountCode();
        String seed = new String();

        if (currentInitCodeList != null && currentInitCodeList.size() > 0) {
            boolean isExist = true;

            while (isExist) {
                isExist = false;
                seed = randomSeed();

                for (Iterator<String> iter = currentInitCodeList.iterator(); iter.hasNext(); ) {
                    String var = iter.next();
                    if (var.equalsIgnoreCase(seed)) {
                        isExist = true;
                        break;
                    }
                }
            }
        } else {
            return randomSeed();
        }

        return seed;
    }


    private static String randomSeed() {
        String seed = "";
        Random random = new Random();
        int tmp;
        for (int i = 1; i <= 10; i++) {
            tmp = random.nextInt(9);
            if (tmp == 0) {
                seed += "0";
            } else {
                seed += tmp;
            }
        }
        return seed;
    }
}
